const axios = require('axios');
const allServices = require('../db');
const config = require('../config')

const recipeApi = async (code) => {
  const res = await axios.get(config.HOST + '/juno/api/v2/recipes/show_v2.json?mode=full&id='+ code)
  const resData = res.data
  if (resData.status === 'error') {
    return await allServices.addErrorLog([resData.msg, code])
  } else {
    const singleDish = resData.content.recipe
    if (singleDish.id) {
      const id = singleDish.id
      const image = singleDish.image.ident || ''
      const name = singleDish.name || ''
      const authorName = singleDish.author.name || ''
      const authorImage = singleDish.author.image.ident || ''
      const score = singleDish.score || ''
      const desc = singleDish.desc || ''
      const n_pv = singleDish.stats.n_pv || ''
      const n_collects = singleDish.stats.n_collects || ''
      const n_dishes = singleDish.stats.n_dishes || ''
      const ingredient = JSON.stringify(singleDish.ingredient || '' )
      let instruction = []
      singleDish.instruction.forEach((item,index) => {
        const step = {
          index: index,
          text: item.text,
          ident: item.ident
        }
        instruction.push(step)
      });
      const data = [
        id,
        image,
        name,
        authorName,
        authorImage,
        score,
        desc,
        n_pv,
        n_collects,
        n_dishes,
        ingredient,
        JSON.stringify(instruction)
      ]
      try {
        return await allServices.addDishComplete(data)
      } catch (error) {
        return await allServices.addErrorLog([error.sqlMessage,singleDish.id])
      }
    } else {
      return '无效数据'
    }
  }
}

module.exports = recipeApi